package com.hdjk.view.activity.personalcenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.activity.main.WebBrowseActivity;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.callback.ListDialogCallBackListener;
import com.hdjk.view.dialog.ListDialog;
import com.hdjk.view.network.Network;
import com.hdjk.view.network.PersonalNetWork;
import com.hdjk.view.util.SharedPreferencesUtil;
import com.hdjk.view.util.StringAppUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.hdjk.view.util.ValidateUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.BaseEntity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 开户页
 * Created by Administrator on 2017/11/4.
 */

public class OpenAccountActivity extends BaseActivity implements View.OnClickListener {
    private String codeToken = "";
    private List<BaseEntity> mBankList;

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private EditText et_name;
    private EditText et_id_card;
    private EditText et_bank_code;
    private RelativeLayout rel_bank;
    private ListDialog ld_bank;
    private EditText et_pwd;
    private EditText et_tel;
    private EditText et_code;
    private TextView tv_send_code;
    private TextView tv_sure;
    private TextView tv_yifeng;
    private TextView tv_xieyi;
    private TextView tv_quanyi;
    private CheckBox cb_read1,cb_read2,cb_read3;
    // End Of Content View Elements

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        et_name = (EditText) findViewById(R.id.et_name);
        et_id_card = (EditText) findViewById(R.id.et_id_card);
        et_bank_code = (EditText) findViewById(R.id.et_bank_code);
        rel_bank = (RelativeLayout) findViewById(R.id.rel_bank);
        ld_bank = (ListDialog) findViewById(R.id.ld_bank);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_tel = (EditText) findViewById(R.id.et_tel);
        et_code = (EditText) findViewById(R.id.et_code);
        tv_send_code = (TextView) findViewById(R.id.tv_send_code);
        tv_sure = (TextView) findViewById(R.id.tv_sure);
        tv_yifeng = (TextView) findViewById(R.id.tv_yifeng);
        tv_xieyi = (TextView) findViewById(R.id.tv_xieyi);
        tv_quanyi = (TextView) findViewById(R.id.tv_quanyi);
        cb_read1 = (CheckBox) findViewById(R.id.cb_read1);
        cb_read2 = (CheckBox) findViewById(R.id.cb_read2);
        cb_read3 = (CheckBox) findViewById(R.id.cb_read3);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_open_account);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        rel_bank.setOnClickListener(this);
        tv_send_code.setOnClickListener(this);
        tv_sure.setOnClickListener(this);
        tv_yifeng.setOnClickListener(this);
        tv_xieyi.setOnClickListener(this);
        tv_quanyi.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        mBankList = new ArrayList<>();
        ld_bank.initData("选择开户银行", mBankList, new ListDialogCallBackListener() {
            @Override
            public void OnChange(int index) {
            }
        });
        getBankList();
    }

    private void getBankList() {
        Network.getBankList(UserTokenUtil.getToken(OpenAccountActivity.this),new CallBackListener() {
            @Override
            public void onCallBackCompleted(Msg msg) {
                if (msg != null) {
                    if (msg.getSuccess()) {
                        if (TextUtils.isEmpty(msg.getResult()))
                            SharedPreferencesUtil.saveBankList(OpenAccountActivity.this, msg.getResult());
                        mBankList = (List<BaseEntity>) msg.getData();
                        ld_bank.notifyDataSetChanged(mBankList);
                    }
                }
            }

            @Override
            public void onCallBackError(Msg msg) {

            }
        });
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tv_send_code.setText("已发送" + (millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            tv_send_code.setEnabled(true);
            tv_send_code.setBackgroundResource(R.drawable.button_yanzhengma_sel);
            tv_send_code.setTextColor(getResources().getColor(R.color.white));
            tv_send_code.setText("获取验证码");
        }
    };

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tv_yifeng:
                showPopupWindow(tv_yifeng);
                break;
            case R.id.tv_quanyi:
                intent = new Intent(this, WebBrowseActivity.class);
                intent.putExtra("title", "");
                intent.putExtra("url", "file:///android_asset/xy_qy.html");
                startActivity(intent);
                break;
            case R.id.tv_xieyi:
                intent = new Intent(this, WebBrowseActivity.class);
                intent.putExtra("title", "");
                intent.putExtra("url", "file:///android_asset/xy_fw.html");
                startActivity(intent);
                break;
            case R.id.rel_bank:
                break;
            case R.id.tv_send_code:
                sendCode();
                break;
            case R.id.tv_sure:
                submit();
                break;
        }
    }

    private void sendCode() {
        String name = et_name.getText().toString();
        String idCard = et_id_card.getText().toString();
        String bankCode = et_bank_code.getText().toString();
        String bank = ld_bank.getItem() >= 0 ? mBankList.get(ld_bank.getItem()).getId() : "";
        String tel = et_tel.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShortToast(this, "请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(idCard)) {
            ToastUtils.showShortToast(this, "请输入身份证号");
            return;
        }
        if (TextUtils.isEmpty(bankCode)) {
            ToastUtils.showShortToast(this, "请输入银行卡号");
            return;
        }
        if (!(ld_bank.getItem() >= 0) || "".equals(bank)) {
            ToastUtils.showShortToast(this, "请选择开户银行");
            return;
        }
        if (TextUtils.isEmpty(tel)) {
            ToastUtils.showShortToast(this, "请输入银行预留手机号");
            return;
        }
        if (!ValidateUtil.isMobileNO(tel)) {
            ToastUtils.showShortToast(this, "请输入正确的手机号码");
            return;
        }
        JSONObject obj = new JSONObject();
        try {
            mDialog.show();
            obj.put("bankNumber", bankCode);
            obj.put("idType", "0");
            obj.put("idName", name);
            obj.put("idNumber", idCard);
            obj.put("telephoneNumber", tel);
            obj.put("bankCode", bank);
            PersonalNetWork.getOpenAccountIdentifyingCode(UserTokenUtil.getToken(OpenAccountActivity.this),obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess()) {
                        codeToken = (String) msg.getData();
                        tv_send_code.setBackgroundResource(R.drawable.utton_yanzhengma_dis);
                        tv_send_code.setTextColor(getResources().getColor(R.color.gray_aaaaaaa));
                        tv_send_code.setEnabled(false);
                        timer.start();
                        ToastUtils.showShortToast(OpenAccountActivity.this, "验证码发送成功");
                    } else {
                        if (msg != null && !TextUtils.isEmpty(msg.getMsg())&&!"null".equals(msg.getMsg())) {
                            ToastUtils.showShortToast(OpenAccountActivity.this, msg.getMsg());
                        } else {
                            ToastUtils.showShortToast(OpenAccountActivity.this, "验证码发送失败");
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void submit() {
        String name = et_name.getText().toString();
        String idCard = et_id_card.getText().toString();
        String bankCode = et_bank_code.getText().toString();
        String bank = ld_bank.getItem() >= 0 ? mBankList.get(ld_bank.getItem()).getId() : "";
        String pwd = et_pwd.getText().toString();
        String tel = et_tel.getText().toString();
        String code = et_code.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShortToast(this, "请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(idCard)) {
            ToastUtils.showShortToast(this, "请输入身份证号");
            return;
        }
        if (TextUtils.isEmpty(bankCode)) {
            ToastUtils.showShortToast(this, "请输入银行卡号");
            return;
        }
        if (!(ld_bank.getItem() >= 0) || "".equals(bank)) {
            ToastUtils.showShortToast(this, "请选择开户银行");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            ToastUtils.showShortToast(this, "请输入交易密码");
            return;
        }
        if (pwd.length()<6||pwd.length()>20){
            ToastUtils.showLongToast(this, "交易密码长度为6-20位");
            return;
        }
        if (TextUtils.isEmpty(tel)) {
            ToastUtils.showShortToast(this, "请输入银行预留手机号");
            return;
        }
        if (!ValidateUtil.isMobileNO(tel)) {
            ToastUtils.showShortToast(this, "请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(code)) {
            ToastUtils.showShortToast(this, "请输入验证码");
            return;
        }
        if (!cb_read1.isChecked()){
            ToastUtils.showShortToast(this, "请先阅读《投资人权益须知》、《奕丰金融平台服务协议》");
            return;
        }
        if (!cb_read2.isChecked()){
            ToastUtils.showShortToast(this, "请先确认无不良诚信记录和交易账户的实际控制投资者为您本人");
            return;
        }
        if (!cb_read3.isChecked()){
            ToastUtils.showShortToast(this, "请先确认您的税收情况");
            return;
        }
        JSONObject obj = new JSONObject();
        try {
            mDialog.show();
            obj.put("bankNumber", bankCode);
            obj.put("idType", "0");
            obj.put("idName", name);
            obj.put("idNumber", idCard);
            obj.put("telHp", tel);
            obj.put("bankCode", bank);
            obj.put("password", pwd);
            obj.put("otp", code);
            obj.put("token", codeToken);
            PersonalNetWork.openAccount(UserTokenUtil.getToken(OpenAccountActivity.this),obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess()) {
                        if (!TextUtils.isEmpty(msg.getResult())){
                            UserTokenUtil.setUserName(OpenAccountActivity.this,msg.getResult());
                            UserTokenUtil.setHoldingCode(OpenAccountActivity.this,1);
                            ToastUtils.showShortToast(OpenAccountActivity.this, "开户成功");
                            back();
                        }
                    } else {
                        if (msg != null && !StringAppUtil.isEmptyOrNull(msg.getMsg())) {
                            ToastUtils.showShortToast(OpenAccountActivity.this, msg.getMsg());
                        } else {
                            ToastUtils.showShortToast(OpenAccountActivity.this, "开户失败");
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
